<template>
  <div class="approval-node">
    <a-form
      :model="data.form"
      name="form"
      label-wrap
      :label-col="{ span: 24 }"
      :wrapper-col="{ span: 24 }"
      autocomplete="off"
    >
      <a-form-item label="节点名称" name="name">
        <a-input v-model:value="data.form.name" placeholder="节点名称"></a-input>
      </a-form-item>
      <a-form-item label="节点类型" name="dataType">
        <a-radio-group v-model:value="data.form.dataType" name="dataType" @change="dataTypeChange">
          <a-radio value="fixed">固定节点</a-radio>
          <a-radio value="dynamic">自由节点</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="data.form.dataType === 'fixed'" name="approveType">
        <template #label> 预置审批人员：<span class="desc">（可不设置，具体使用时可修改）</span> </template>
        <SetMember
          :key="data.form.id"
          v-model:memberType="data.form.memberType"
          v-model:memberList="data.form.memberList"
          :gain-type="isConfig() ? 'role' : ''"
          @change="memberChange"
        />
      </a-form-item>
      <a-form-item v-else name="approveType">
        <a-select v-model:value="data.form.nodeSetupType">
          <a-select-option v-for="item in dynamicOptions" :key="item.value" :value="item.value">{{
            item.label
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="审批方式" name="multiInstance">
        <a-radio-group v-model:value="data.form.multiInstance" name="multiInstance" @change="multiInstanceChange">
          <a-radio value="parallel">多人时并行审批</a-radio>
          <a-radio value="serial">多人时串行审批</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="审批结果产生方式" name="resultType" @change="resultTypeChange">
        <a-radio-group
          v-model:value="data.form.resultType"
          name="resultType"
          :disabled="data.form.multiInstanceLoopCharacteristics.isSequential"
        >
          <a-radio value="every">所有审批人同意</a-radio>
          <a-radio value="one">任一审批人同意或退回</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="退回至" name="backTo">
        <a-radio-group v-model:value="data.form.backTo" name="backTo" @change="backToChange">
          <a-radio value="Flow_0000002">起始节点</a-radio>
          <a-radio value="assignee">指定节点</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="data.form.backTo === 'assignee'">
        <a-select v-model:value="data.form.returnTo">
          <a-select-option v-for="item in nodes" :key="item.id" :value="item.id">{{
            item.properties.name
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="data.form.backTo === 'Flow_0000002'" label="退回修改后重审起点" name="backStartNode">
        <a-radio-group v-model:value="data.form.backStartNode" name="backStartNode" @change="backStartNodeChange">
          <!-- <a-radio value="Flow_0000002">起始节点</a-radio> -->
          <a-radio :value="id">当前节点</a-radio>
          <a-radio value="assignee">指定节点</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="data.form.backTo === 'Flow_0000002' && data.form.backStartNode === 'assignee'">
        <a-select v-model:value="data.form.returnUpdateAfterApprovalNode">
          <a-select-option v-for="item in nodes" :key="item.id" :value="item.id">{{
            item.properties.name
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="发起人可见" name="initiatorVisible">
        <a-checkbox v-model:checked="data.form.initiatorVisible">允许发起人查看当前节点的审批结果</a-checkbox>
      </a-form-item>
      <a-form-item label="去重处理" name="toRepeat">
        <a-checkbox v-model:checked="data.form.toRepeat">如果审批人员在前面相邻节点已审批，则自动跳过</a-checkbox>
      </a-form-item>
      <a-form-item v-if="!hideSignSetting" label="电子签署主体" name="signFlag">
        <a-checkbox v-model:checked="data.form.signFlag">当前节点审批过程中需要签署相应文件</a-checkbox>
        <p style="color: rgb(234, 168, 69)">（具体需要签署的文件请在“文件清单”中配置）</p>

        <span
          v-if="orgInfo.esignFlag === 0"
          class="error"
          style="display: inline-block; vertical-align: top; margin-left: 5px"
        >
          <InfoCircleOutlined style="width: 20px; margin-top: 1px" />
          <span style="vertical-align: top">本组织未开启电子签署，暂不支持使用此功能，请联系组织管理员</span>
        </span>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup name="ApprovalNode">
import { reactive, ref, watch, onBeforeUnmount, onMounted, computed } from 'vue'
import SetMember from '@@/components/setMember/index.vue'
import { isConfig } from '@@/utils/index'
import { InfoCircleOutlined } from '@vicons/antd'
import { storage } from '@@/utils/Storage'
const orgInfo = storage.get('ORGINFO')
const emit = defineEmits(['close'])

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  currentNode: {
    type: Object,
    default: () => {}
  },
  lf: {
    type: Object,
    default: () => {}
  },
  hideSignSetting: {
    tyoe: Boolean,
    default: false
  }
})
interface IData {
  form: IForm
  id: string | number
}
interface IForm {
  id: string | number
  name: string
  memberType: number
  nodeSetupType: number | string
  multiInstance: string
  resultType: string
  backTo: string
  returnTo: string
  backStartNode: string
  returnUpdateAfterApprovalNode: string
  initiatorVisible: boolean
  toRepeat: boolean
  signFlag: boolean
  multiInstanceLoopCharacteristics: any
  candidateUsers: string
  candidateUsersShow: string
  candidateUsersName: string
  candidateGroups: string
  candidateGroupsShow: string
  candidateGroupsName: string
  dataType: string
  memberList?: Array<any>
}
const initForm = () => {
  return {
    id: '',
    name: '',
    memberType: 1,
    nodeSetupType: '',
    multiInstance: 'parallel',
    resultType: 'one',
    backTo: 'Flow_0000002',
    returnTo: '',
    backStartNode: '',
    returnUpdateAfterApprovalNode: '',
    initiatorVisible: false,
    signFlag: false,
    toRepeat: false,
    multiInstanceLoopCharacteristics: {},
    candidateUsers: '',
    candidateUsersShow: '',
    candidateUsersName: '',
    candidateGroups: '',
    candidateGroupsShow: '',
    candidateGroupsName: '',
    dataType: '',
    memberList: []
  }
}
const data = reactive<IData>({
  id: '',
  form: initForm()
})
const id = ref()

const dynamicOptions = reactive([
  {
    label: '发起人设置节点审批人',
    value: 1
  },
  {
    label: '上一节点审批人设置当前节点审批人',
    value: 2
  }
])

// 初始化节点属性数据
const init = () => {
  id.value = props.currentNode.data.id
  data.form = props.currentNode.data.properties
  data.form.backStartNode = data.form.backStartNode || (nodes.value.length ? 'assignee' : id.value)
  data.form.returnUpdateAfterApprovalNode =
    data.form.returnUpdateAfterApprovalNode || (nodes.value.length ? nodes.value[0].id : id.value)
  // 如果退回至节点被删除了，默认退回至起始节点
  const backItem = nodes.value.find((el) => el.id === data.form.returnTo)
  if (!backItem) {
    data.form.returnTo = 'Flow_0000002'
    data.form.backTo = 'Flow_0000002'
  }
  // 如果退回重审节点被删除了，默认当前节点为重申节点
  const returnItem = nodes.value.find((el) => el.id === data.form.returnUpdateAfterApprovalNode)
  if (!returnItem) {
    data.form.backStartNode = nodes.value.length ? 'assignee' : id.value
    data.form.returnUpdateAfterApprovalNode = nodes.value.length ? nodes.value[0].id : id.value
  }
  data.form.multiInstanceLoopCharacteristics['flowable:collection'] = id.value + '_approvalList'
  const { candidateUsers, candidateUsersName, candidateGroups, candidateGroupsName } = data.form
  // 将后端传过来的审批人或角色转换成数组格式
  if (candidateUsers && candidateUsersName) {
    const candidateUsersArr = (candidateUsers || '').split(',')
    const candidateUsersNameArr = (candidateUsersName || '').split(',')

    data.form.memberList = candidateUsersArr.map((el, index) => {
      return {
        label: candidateUsersNameArr[index],
        value: el
      }
    })
  } else if (candidateGroups && candidateGroupsName) {
    const candidateUsersArr = (candidateGroups || '').split(',')
    const candidateUsersNameArr = (candidateGroupsName || '').split(',')

    data.form.memberList = candidateUsersArr.map((el, index) => {
      return {
        label: candidateUsersNameArr[index],
        value: el
      }
    })
  }
}
watch(
  () => props.currentNode.data.id,
  (val, oldVal) => {
    emit('close', data.form, oldVal)
    id.value = val
    data.form.id = id.value
    init()
  }
)

onMounted(() => {
  init()
})

const nodes = computed(() => {
  const arr = props.lf.graphModel.nodes.filter((el) => {
    return el.type === 'userTask' && el.properties.name !== '抄送节点' && el.properties.name !== '发起节点'
  })
  return arr
})

const multiInstanceChange = (el) => {
  data.form.multiInstanceLoopCharacteristics.isSequential = el.target.value === 'serial'
  if (el.target.value === 'serial') {
    data.form.resultType = 'every'
    data.form.multiInstanceLoopCharacteristics.completionCondition.value = 1
  }
}
const resultTypeChange = (el) => {
  data.form.multiInstanceLoopCharacteristics.completionCondition.value = el.target.value === 'every' ? 1 : 0.001
}
const dataTypeChange = (el) => {
  if (el.target.value === 'dynamic') {
    data.form.memberList = []
    // ${approval}为工作流必要参数
    data.form.candidateUsers = '${approval}'
    data.form.candidateUsersShow = ''
    data.form.candidateUsersName = ''
    data.form.candidateGroups = '${approval}'
    data.form.candidateGroupsShow = ''
    data.form.candidateGroupsName = ''
    data.form.nodeSetupType = ''
  } else {
    data.form.candidateUsers = ''
    data.form.candidateGroups = ''
    data.form.nodeSetupType = ''
  }
}
const memberChange = () => {
  const temArr = (data.form.memberList || []).map((el) => el.value)
  const temNameArr = (data.form.memberList || []).map((el) => el.label)
  if (data.form.memberType === 0) {
    data.form.candidateUsers = temArr.join(',')
    data.form.candidateUsersShow = temArr.join(',')
    data.form.candidateUsersName = temNameArr.join(',')
    data.form.candidateGroups = ''
    data.form.candidateGroupsShow = ''
    data.form.candidateGroupsName = ''
  } else {
    data.form.candidateGroups = temArr.join(',')
    data.form.candidateGroupsShow = temArr.join(',')
    data.form.candidateGroupsName = temNameArr.join(',')
    data.form.candidateUsers = ''
    data.form.candidateUsersShow = ''
    data.form.candidateUsersName = ''
  }
}
const backToChange = (el) => {
  if (el.target.value !== 'assignee') {
    data.form.returnTo = el.target.value
  } else {
    data.form.returnTo = ''
    data.form.backStartNode = nodes.value.length ? 'assignee' : id.value
    data.form.returnUpdateAfterApprovalNode = nodes.value.length ? nodes.value[0].id : id.value
  }
}
const backStartNodeChange = (el) => {
  if (el.target.value !== 'assignee') {
    data.form.returnUpdateAfterApprovalNode = el.target.value
  } else {
    data.form.returnUpdateAfterApprovalNode = nodes.value.length ? nodes.value[0].id : id.value
  }
}
// 切换components时触发
onBeforeUnmount(() => {
  if (data.form.dataType === 'fixed') {
    const temArr = (data.form.memberList || []).map((el) => el.value)
    const temNameArr = (data.form.memberList || []).map((el) => el.titleLabel || el.label)
    if (data.form.memberType === 0) {
      data.form.candidateUsers = temArr.join(',')
      data.form.candidateUsersShow = temArr.join(',')
      data.form.candidateUsersName = temNameArr.join(',')
      data.form.candidateGroups = ''
      data.form.candidateGroupsShow = ''
      data.form.candidateGroupsName = ''
    } else {
      data.form.candidateGroups = temArr.join(',')
      data.form.candidateGroupsShow = temArr.join(',')
      data.form.candidateGroupsName = temNameArr.join(',')
      data.form.candidateUsers = ''
      data.form.candidateUsersShow = ''
      data.form.candidateUsersName = ''
    }
    delete data.form.memberList
  }

  emit('close', data.form, id.value)
})
const close = () => {
  emit('close', data.form, id.value)
}
defineExpose({
  close
})
</script>
<style lang="less">
.approval-node {
  width: 350px;
  .desc {
    font-size: 14px;
    color: #999;
  }
}
</style>
